package com.taojin.shoppinginterest.adapter;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.lidroid.xutils.BitmapUtils;
import com.taojin.shoppinginterest.R;
import com.taojin.shoppinginterest.bean.Poster;
import com.taojin.shoppinginterest.utils.BitmapHelper;
import com.taojin.shoppinginterest.widget.RecyclingPagerAdapter;

import java.util.List;

/**
 * Created by T400 on 15-5-12.
 */
public class AutoScrollAdapter extends RecyclingPagerAdapter implements ViewPager.OnPageChangeListener{
    private Context context;
    private List<Poster> posters;
    private LinearLayout dotLayout;
    private BitmapUtils bitmapUtils;

    public AutoScrollAdapter(Context context, List<Poster> posters,LinearLayout dotLayout) {
        this.context = context;
        this.posters = posters;
        this.dotLayout=dotLayout;
        bitmapUtils= BitmapHelper.getInstance().getBitmapUtils(context,R.mipmap.icon,R.mipmap.icon);
    }

    @Override
    public int getCount() {
        return posters.size();
    }



    @Override
    public View getView(int position, View convertView, ViewGroup container) {
        ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder(context);
            convertView = holder.imageView;
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        bitmapUtils.display(holder.imageView, posters.get(getCurrentPosition(position)).getImg_url());
        return convertView;
    }



    private static class ViewHolder {
        ImageView imageView;
        public ViewHolder(Context context) {
            imageView = new ImageView(context);
            imageView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
        }
    }



    private int getCurrentPosition(int position) {
        return position % posters.size();
    }
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {

        for (int i = 0; i < dotLayout.getChildCount(); i++) {
                View view=dotLayout.getChildAt(i);
            if (getCurrentPosition(position) == i) {
                view.setBackgroundResource(R.drawable.dot_shape2);
            } else {
                view.setBackgroundResource(R.drawable.dot_shape);
            }
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}
